#include "userService.h"

/**
 *  sqlite3_prepare_v2函数
 *  int sqlite3_prepare_v2(
        sqlite3 *db,            // 数据库连接
        const char *zSql,       // SQL语句
        int nByte,              // SQL长度（-1表示自动计算）
        sqlite3_stmt **ppStmt,  // 输出：预处理语句句柄
        const char **pzTail     // 输出：未处理的SQL尾端
    );
 *
 *      绑定不同类型的参数
        int sqlite3_bind_int(sqlite3_stmt*, int param_index, int value);
        int sqlite3_bind_text(sqlite3_stmt*, int param_index, const char*, int n, void(*)(void*));
        int sqlite3_bind_double(sqlite3_stmt*, int param_index, double value);
        int sqlite3_bind_null(sqlite3_stmt*, int param_index);
 *      参数说明：
            param_index 参数索引（从 1 开始），对应 SQL 中的?占位符。
            n 字符串长度（-1 表示自动计算）。
            destructor 内存释放函数（通常用SQLITE_STATIC或SQLITE_TRANSIENT）。
*/

// 创建用户表
int create_user_table(sqlite3 *db) {
    const char *sql = "CREATE TABLE IF NOT EXISTS users ("
                      "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                      "username TEXT UNIQUE NOT NULL,"
                      "password TEXT NOT NULL,"
                      "secret_key TEXT NOT NULL);";

    return sqlite3_exec(db, sql, 0, 0, 0);
}

// 添加用户 插入成功返回: SQLITE_OK -> 0
int insert_user(sqlite3 *db, const User *user) {
    sqlite3_stmt *stmt;
    const char *sql = "INSERT INTO users (username, password,secret_key) VALUES (?, ?, ?);";
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);

    if (rc != SQLITE_OK)
        return rc;

    sqlite3_bind_text(stmt, 1, user->username, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 2, user->password, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 3, user->secret_key, -1, SQLITE_STATIC);
    // 作用：执行预处理语句，返回结果状态：
    // SQLITE_ROW：查询有下一行结果。
    // SQLITE_DONE：操作完成（如 INSERT/UPDATE）。
    rc = sqlite3_step(stmt);
    // 释放预处理语句占用的资源，必须在使用完毕后调用。
    sqlite3_finalize(stmt);
    return rc == SQLITE_DONE ? SQLITE_OK : rc;
}

// 根据ID查询用户
int select_user_by_id(sqlite3 *db, int id, User *user) {
    sqlite3_stmt *stmt;
    const char *sql = "SELECT * FROM users WHERE id = ?;";
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);

    if (rc != SQLITE_OK)
        return rc;

    sqlite3_bind_int(stmt, 1, id);
    rc = sqlite3_step(stmt);

    if (rc == SQLITE_ROW) {
        user->id = sqlite3_column_int(stmt, 0);
        strncpy(user->username, (const char *)sqlite3_column_text(stmt, 1), 19);
        strncpy(user->password, (const char *)sqlite3_column_text(stmt, 2), 19);
        strncpy(user->secret_key, (const char *)sqlite3_column_text(stmt, 3), 63);
        user->username[19] = '\0';
        user->password[19] = '\0';
        user->secret_key[63] = '\0';
    }

    sqlite3_finalize(stmt);
    return rc == SQLITE_ROW ? SQLITE_OK : SQLITE_ERROR;
}

// 根据用户名查询用户
int select_user_by_username(sqlite3 *db, const char *username, User *user) {
    sqlite3_stmt *stmt;
    const char *sql = "SELECT * FROM users WHERE username = ?;";
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);

    if (rc != SQLITE_OK)
        return rc;

    sqlite3_bind_text(stmt, 1, username, -1, SQLITE_STATIC);
    rc = sqlite3_step(stmt);

    if (rc == SQLITE_ROW) {
        user->id = sqlite3_column_int(stmt, 0);
        strncpy(user->username, (const char *)sqlite3_column_text(stmt, 1), 19);
        strncpy(user->password, (const char *)sqlite3_column_text(stmt, 2), 19);
        strncpy(user->secret_key, (const char *)sqlite3_column_text(stmt, 3), 63);
        user->username[19] = '\0';
        user->password[19] = '\0';
        user->secret_key[63] = '\0';
    }

    sqlite3_finalize(stmt);
    return rc == SQLITE_ROW ? SQLITE_OK : SQLITE_ERROR;
}

// 更新用户信息
int update_user(sqlite3 *db, const User *user) {
    sqlite3_stmt *stmt;
    const char *sql = "UPDATE users SET username = ?, password = ? WHERE id = ?;";
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);

    if (rc != SQLITE_OK)
        return rc;

    sqlite3_bind_text(stmt, 1, user->username, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 2, user->password, -1, SQLITE_STATIC);
    sqlite3_bind_int(stmt, 3, user->id);

    rc = sqlite3_step(stmt);
    sqlite3_finalize(stmt);
    return rc == SQLITE_DONE ? SQLITE_OK : rc;
}

// 删除用户
int delete_user(sqlite3 *db, int id) {
    sqlite3_stmt *stmt;
    const char *sql = "DELETE FROM users WHERE id = ?;";
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);

    if (rc != SQLITE_OK)
        return rc;

    sqlite3_bind_int(stmt, 1, id);
    rc = sqlite3_step(stmt);
    sqlite3_finalize(stmt);
    return rc == SQLITE_DONE ? SQLITE_OK : rc;
}

// 获取所有用户（使用回调函数处理结果）
int select_all_users(sqlite3 *db, int (*callback)(void *, const User *), void *data) {
    sqlite3_stmt *stmt;
    const char *sql = "SELECT * FROM users;";
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);

    if (rc != SQLITE_OK)
        return rc;

    User user;
    while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
        user.id = sqlite3_column_int(stmt, 0);
        strncpy(user.username, (const char *)sqlite3_column_text(stmt, 1), 19);
        strncpy(user.password, (const char *)sqlite3_column_text(stmt, 2), 19);
        strncpy(user.secret_key, (const char *)sqlite3_column_text(stmt, 3), 63);
        user.username[19] = '\0';
        user.password[19] = '\0';
        user.secret_key[63] = '\0';

        if (callback && callback(data, &user) != 0) {
            break; // 回调请求终止
        }
    }

    sqlite3_finalize(stmt);
    return rc == SQLITE_DONE ? SQLITE_OK : rc;
}